﻿using ManagementApi.Mvc;
using ManagementApi.Mvc.ApplicationContexts;
using Modules.Corp;
using Modules.Person;
using Modules.Project;
using Modules.Project.Entitys;
using Modules.System.User;
using PmSoft;
using PmSoft.Entity;
using PmSoft.Exceptions;

namespace ManagementApi.Authorizers
{

    [UseDI(ServiceLifetime.Scoped)]
    public class PersonContractOwnAuthorizer
    {
        private readonly PersonCorpContractService personCorpContractService;
        private readonly PersonService personService;
        private readonly CorpService corpService;
        private readonly ProjectCorpService projectCorpService;
        private readonly ProjectService projectService;
        private readonly ManagementApplicationContext applicationContext;
        private readonly ProjectOwnAuthorizer projectOwnAuthorizer;

        public PersonContractOwnAuthorizer(PersonCorpContractService personCorpContractService, PersonService personService, CorpService corpService, ProjectCorpService projectCorpService, ProjectService projectService, ManagementApplicationContext applicationContext, ProjectOwnAuthorizer projectOwnAuthorizer)
        {
            this.personCorpContractService = personCorpContractService;
            this.personService = personService;
            this.corpService = corpService;
            this.projectCorpService = projectCorpService;
            this.projectService = projectService;
            this.applicationContext = applicationContext;
            this.projectOwnAuthorizer = projectOwnAuthorizer;
        }

        /// <summary>
        /// 检查并抛出数据权限验证失败信息
        /// </summary>
        /// <param name="personContractId"></param>
        /// <exception cref="OwnAuthorizationFailedException"></exception>
        public void CheckAndThrowIfOwnAuthenticationFailed(int personContractId)
        {
            var personContract = personCorpContractService.GetPersonCorpContract(personContractId) ?? throw new BusinessException("数据不存在");
            projectOwnAuthorizer.CheckAndThrowIfOwnAuthenticationFailed(personContract.ProjectId);
        }

        /// <summary>
        /// 检查并抛出数据权限验证失败信息
        /// </summary>
        /// <param name="personContractIds"></param>
        public void CheckAndThrowIfOwnAuthenticationFailed(IEnumerable<int> personContractIds)
        {
            foreach (int personContractId in personContractIds)
            {
                CheckAndThrowIfOwnAuthenticationFailed(personContractId);
            }
        }
    }
}